package com.cs249;

import java.io.BufferedReader;
import java.io.FileReader;

public class GoogleInterview {

	public static String reverse(String text) {
		int length = text.length();
		int last = length - 1;
		char[] textArray = text.toCharArray();
		for (int i = 0; i < length / 2; i++) {
			char c = textArray[i];
			textArray[i] = textArray[last - i];
			textArray[last - i] = c;
		}
		return new String(textArray);

	}

	public static void multTables(int max) {
		for (int i = 1; i <= max; i++) {
			for (int j = 1; j <= max; j++) {
				System.out.print(String.format("%4d", j * i));
			}
			System.out.println();
		}
	}

	/**
	 * Fibonacci_(n) = Fibonacci_(n - 1) + Fibonacci_(n - 2)
	 * 
	 * @param n
	 * @return
	 */
	public static long fib(int n) {
		return n <= 0 ? 0 : fib2(n, 0, 1);
	}

	/**
	 * Fibonacci_(n) = Fibonacci_(n - 1) + Fibonacci_(n - 2)
	 * 
	 * @param n
	 * @param p0
	 * @param p1
	 * @return
	 */
	public static long fib2(int n, long p0, long p1) {
		return n == 1 ? p1 : fib2(n - 1, p1, p0 + p1);
	}

	public static void printOdds(int n) {
		System.out.println(n + " odd numbers");
		for (int i = 1; i < n; i += 2) {
			System.out.println(i);
		}
	}

	public static void sumFile(String name) {
		try {
			int total = 0;
			BufferedReader in = new BufferedReader(new FileReader(name));
			for (String s = in.readLine(); s != null; s = in.readLine()) {
				total += Integer.parseInt(s);
			}
			System.out.println(total);
			in.close();
		} catch (Exception xc) {
			xc.printStackTrace();
		}
	}

	public static int largest(int[] input) {
		int max = Integer.MIN_VALUE;
		for (int i = 0; i < input.length; i++) {
			if (input[i] > max)
				max = input[i];
		}
		return max;
	}

	public static void main(String[] args) {
		String text = "Hello World";
		System.out.println(" Reverse of " + text + " is " + reverse(text));

		multTables(15);

		for (int i = 1; i <= 16; i++) {
			System.out.println("Fibonacci number-th " + i + " is " + fib(i));
		}

		printOdds(100);
	}
}
